package com.cl.security.system.controller;

import cn.hutool.json.JSONUtil;
import com.cl.security.base.controller.BaseController;
import com.cl.security.common.result.CommonResult;
import com.cl.security.system.entity.Permission;
import com.cl.security.system.entity.User;
import com.cl.security.system.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
*
* @author chenlong
* @date 2020/12/8
*/
@RestController
@RequestMapping("user")
public class UserController extends BaseController<User,UserService> {
    private final UserService userService ;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    public UserController(UserService service) {
        super(service, User.class);
        this.userService = service;
    }


    @PostMapping("saveAvatar")
    public CommonResult saveAvatar(@RequestParam("file") MultipartFile avatar,Long id) {
        return userService.saveAvatar(avatar,id);
    }
    @GetMapping("examPassword")
    public CommonResult examPassword(Long id, String password) {
        return userService.examPassword(id, password);
    }

    @PostMapping("save")
    public CommonResult save(String  data) {
        return userService.save(JSONUtil.toBean(data.substring(1,data.length()-1),User.class));
    }

    @PostMapping("login")
    public CommonResult login(User user) {
        String token = userService.login(user.getUsername(), user.getPassword());
        if (token == null) {
            return CommonResult.validateFailed("用户名或密码错误");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead);
        return CommonResult.success(tokenMap);
    }
    @GetMapping("permission")
    public CommonResult<Set<Permission>> getPermissionList(HttpServletRequest request) {
        Long userId = userService.getUserIdFromRequest(request);
        Set<Permission> permissions = userService.listPermission(userId);
        return CommonResult.success(permissions);
    }

    @GetMapping("info")
    public CommonResult<User> getUserInfo(String token) {
        return CommonResult.success(userService.getUserByToken(token));
    }
    @PostMapping("logout")
    public CommonResult logout() {
        return CommonResult.success(null);
    }
}
